<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>咨询管理 - 管理员端</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .chat-container {
            max-width: 1400px;
            margin: 20px auto;
            height: calc(100vh - 200px);
            display: flex;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            overflow: hidden;
        }
        .chat-sidebar {
            width: 350px;
            border-right: 1px solid #dee2e6;
            background-color: #f8f9fa;
            overflow-y: auto;
        }
        .chat-main {
            flex: 1;
            display: flex;
            flex-direction: column;
        }
        .chat-header {
            padding: 15px 20px;
            border-bottom: 1px solid #dee2e6;
            background-color: #fff;
        }
        .chat-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f8f9fa;
        }
        .message {
            margin-bottom: 15px;
            display: flex;
        }
        .message.user {
            justify-content: flex-end;
        }
        .message.merchant {
            justify-content: flex-start;
        }
        .message-content {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 8px;
            word-wrap: break-word;
        }
        .message.user .message-content {
            background-color: #007bff;
            color: white;
        }
        .message.merchant .message-content {
            background-color: white;
            color: #333;
            border: 1px solid #dee2e6;
        }
        .message-time {
            font-size: 12px;
            color: #6c757d;
            margin-top: 5px;
        }
        .session-item {
            padding: 15px;
            border-bottom: 1px solid #dee2e6;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        .session-item:hover {
            background-color: #e9ecef;
        }
        .session-item.active {
            background-color: #007bff;
            color: white;
        }
        .session-item.active .session-user,
        .session-item.active .session-merchant,
        .session-item.active .session-last-message {
            color: rgba(255,255,255,0.9);
        }
        .session-user {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .session-merchant {
            font-size: 13px;
            margin-bottom: 5px;
        }
        .session-last-message {
            font-size: 12px;
            color: #6c757d;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        .session-time {
            font-size: 11px;
            color: #6c757d;
            margin-top: 3px;
        }
        .session-item.active .session-time {
            color: rgba(255,255,255,0.7);
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container-fluid">
        <div class="row">
            <jsp:include page="../common/sidebar.jsp"/>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="pt-3">
                    <h1 class="h2 mb-4">咨询管理</h1>
                    
                    <c:if test="${error != null}">
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            ${error}
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    </c:if>
                    
                    <div class="chat-container">
                        <!-- 左侧会话列表 -->
                        <div class="chat-sidebar">
                            <h5 class="p-3 mb-0 border-bottom">咨询列表</h5>
                            <div id="sessionList">
                                <c:forEach var="session" items="${sessions}">
                                    <div class="session-item" 
                                         data-session-id="${session.sessionId}"
                                         onclick="loadSession('${session.sessionId}', '${session.productName}')">
                                        <div class="session-user">
                                            用户：${session.user != null ? session.user.username : '未知用户'}
                                        </div>
                                        <div class="session-merchant">
                                            商家：${session.merchant != null ? session.merchant.username : '未知商家'}
                                        </div>
                                        <div class="session-last-message">${session.lastMessage != null ? session.lastMessage : '暂无消息'}</div>
                                        <div class="session-time">
                                            <fmt:formatDate value="${session.lastMessageTime}" pattern="yyyy-MM-dd HH:mm"/>
                                        </div>
                                    </div>
                                </c:forEach>
                                <c:if test="${empty sessions}">
                                    <div class="text-center text-muted p-4">暂无咨询</div>
                                </c:if>
                            </div>
                            
                            <!-- 分页 -->
                            <c:if test="${totalPages > 0}">
                                <nav aria-label="咨询分页" class="p-3 border-top">
                                    <ul class="pagination pagination-sm justify-content-center mb-0">
                                        <li class="page-item ${page == 1 ? 'disabled' : ''}">
                                            <a class="page-link" href="${pageContext.request.contextPath}/admin/consultation?page=${page - 1}">上一页</a>
                                        </li>
                                        <c:forEach var="i" begin="1" end="${totalPages}">
                                            <li class="page-item ${page == i ? 'active' : ''}">
                                                <a class="page-link" href="${pageContext.request.contextPath}/admin/consultation?page=${i}">${i}</a>
                                            </li>
                                        </c:forEach>
                                        <li class="page-item ${page == totalPages ? 'disabled' : ''}">
                                            <a class="page-link" href="${pageContext.request.contextPath}/admin/consultation?page=${page + 1}">下一页</a>
                                        </li>
                                    </ul>
                                    <div class="text-center text-muted mt-2" style="font-size: 12px;">
                                        共 ${totalCount} 条，第 ${page}/${totalPages} 页
                                    </div>
                                </nav>
                            </c:if>
                        </div>
                        
                        <!-- 右侧聊天区域 -->
                        <div class="chat-main">
                            <div class="chat-header">
                                <h5 id="chatTitle">请选择咨询会话</h5>
                            </div>
                            <div class="chat-messages" id="chatMessages">
                                <div class="text-center text-muted mt-5">
                                    <p>请选择左侧的咨询会话查看聊天记录</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentSessionId = null;
        let currentProductName = null;
        
        // 加载会话
        function loadSession(sessionId, productName) {
            currentSessionId = sessionId;
            currentProductName = productName;
            
            // 更新UI
            document.getElementById('chatTitle').textContent = '咨询：' + productName;
            
            // 更新会话列表选中状态
            document.querySelectorAll('.session-item').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-session-id') === sessionId) {
                    item.classList.add('active');
                }
            });
            
            // 加载历史消息
            loadHistoryMessages();
        }
        
        // 加载历史消息
        function loadHistoryMessages() {
            if (!currentSessionId) {
                return;
            }
            
            fetch('${pageContext.request.contextPath}/admin/consultation?action=history&sessionId=' + currentSessionId)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.messages) {
                        const messagesDiv = document.getElementById('chatMessages');
                        messagesDiv.innerHTML = '';
                        data.messages.forEach(msg => {
                            // 管理员端：用户的消息显示在右边（user类），商家的消息显示在左边（merchant类）
                            displayMessage(msg.content, msg.senderType === 0 ? 'user' : 'merchant', new Date(msg.createTime));
                        });
                    } else {
                        const messagesDiv = document.getElementById('chatMessages');
                        messagesDiv.innerHTML = '<div class="text-center text-muted mt-5">暂无聊天记录</div>';
                    }
                })
                .catch(error => {
                    console.error('加载历史消息失败:', error);
                    const messagesDiv = document.getElementById('chatMessages');
                    messagesDiv.innerHTML = '<div class="text-center text-danger mt-5">加载聊天记录失败</div>';
                });
        }
        
        // 显示消息
        function displayMessage(content, senderType, time) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = 'message ' + senderType;
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            contentDiv.textContent = content;
            
            const timeDiv = document.createElement('div');
            timeDiv.className = 'message-time';
            timeDiv.textContent = formatTime(time);
            
            contentDiv.appendChild(timeDiv);
            messageDiv.appendChild(contentDiv);
            messagesDiv.appendChild(messageDiv);
            
            // 滚动到底部
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 格式化时间
        function formatTime(date) {
            if (!date || !(date instanceof Date)) {
                date = new Date();
            }
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return hours + ':' + minutes;
        }
    </script>
</body>
</html>

